/* ========== 工具 ========== */
const $ = q => document.querySelector(q);
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

/* 数字滚动 */
function animateCounter(el) {
    const target = +el.dataset.target;
    const duration = 2000;
    const step = target / (duration / 16);
    let now = 0;
    const tick = () => {
        now += step;
        if (now >= target) {
            el.textContent = target.toLocaleString();
            return;
        }
        el.textContent = Math.floor(now).toLocaleString();
        requestAnimationFrame(tick);
    };
    tick();
}

/* 全屏 */
const fullscreenBtn = document.querySelector('#fullscreenBtn');
if (fullscreenBtn) {
    // 全屏切换函数
    function toggleFullscreen() {
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            document.documentElement.requestFullscreen({
                navigationUI: 'hide' // 隐藏导航UI
            }).catch(err => {
                console.error('全屏请求失败:', err);
            });
        }
    }
    
    // 点击按钮切换全屏
    fullscreenBtn.addEventListener('click', toggleFullscreen);
    
    // 阻止其他方式退出全屏（如ESC键）
    document.addEventListener('fullscreenchange', (event) => {
        // 只有在全屏状态下才阻止默认行为
        if (document.fullscreenElement) {
            // 这里不需要做任何事，只是监听状态变化
            console.log('进入全屏模式');
        }
    });
    
    // 阻止ESC键退出全屏
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && document.fullscreenElement) {
            event.preventDefault();
            console.log('阻止ESC键退出全屏');
        }
    });
    
    // 确保按钮在全屏状态下仍能使用
    document.addEventListener('fullscreenerror', (error) => {
        console.error('全屏错误:', error);
    });
}

/* 更新时间显示 */
function updateTimeDisplay() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    $('#updateTime').textContent = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateTimeDisplay, 1000);
updateTimeDisplay();

/* 初始化所有计数器 */
document.querySelectorAll('.counter').forEach(animateCounter);

/* 添加样式，优化中国地图容器 */
// 移除了地图卡片高度和宽度的特殊设置，保持与其他卡片一致

/* ========== 可视化图表 ========== */

/* 1. 中国地图 */
const mapChart = echarts.init($('#chinaMap'));
// 中国主要城市数据
let chinaCityData = [
    { name: '北京', value: [116.3974, 39.9093, random(8, 20)] },
    { name: '上海', value: [121.4737, 31.2304, random(8, 20)] },
    { name: '广州', value: [113.2644, 23.1291, random(8, 20)] },
    { name: '深圳', value: [114.0579, 22.5431, random(8, 20)] },
    { name: '杭州', value: [120.1551, 30.2741, random(8, 20)] },
    { name: '成都', value: [104.0665, 30.5728, random(8, 20)] },
    { name: '武汉', value: [114.3055, 30.5928, random(8, 20)] },
    { name: '西安', value: [108.9481, 34.2658, random(8, 20)] },
    { name: '南京', value: [118.7969, 32.0603, random(8, 20)] },
    { name: '重庆', value: [106.5349, 29.5633, random(8, 20)] },
    { name: '长沙', value: [112.9822, 28.1941, random(8, 20)] },
    { name: '天津', value: [117.2009, 39.0851, random(8, 20)] },
    { name: '苏州', value: [120.5853, 31.2989, random(8, 20)] },
    { name: '郑州', value: [113.6253, 34.7466, random(8, 20)] },
    { name: '青岛', value: [120.3826, 36.0671, random(8, 20)] }
];

// 创建中国地图内的飞线效果
function createFlyLinesData() {
    const lines = [];
    // 以北京为中心
    const center = [116.3974, 39.9093];
    
    chinaCityData.forEach(item => {
        if (item.name !== '北京') { // 从其他城市飞向北京
            lines.push({
                coords: [
                    item.value.slice(0, 2),
                    center
                ],
                value: item.value[2]
            });
        }
    });
    return lines;
}

mapChart.setOption({
    backgroundColor: 'transparent',
    tooltip: {
        trigger: 'item',
        formatter: function(params) {
            if (params.dataType === 'edge') {
                // 找到对应的城市名称
                const city = chinaCityData.find(item => 
                    item.value[0] === params.data.coords[0][0] && 
                    item.value[1] === params.data.coords[0][1]
                );
                return `${city ? city.name : '未知城市'} -> 北京<br/>访问量: ${params.data.value}`;
            }
            return `${params.name}<br/>访问量: ${params.value[2]}`;
        }
    },
    geo: {
        map: 'china',
        roam: true,
        zoom: 1.5, // 放大地图显示
        center: [104.1, 35.8], // 调整地图中心位置使其居中
        itemStyle: {
            areaColor: 'rgba(0,212,255,.15)',
            borderColor: '#00d4ff'
        },
        emphasis: { itemStyle: { areaColor: 'rgba(0,212,255,.35)' } }
    },
    series: [
        // 飞线效果
        {
            type: 'lines',
            coordinateSystem: 'geo',
            data: createFlyLinesData(),
            lineStyle: {
                width: 2,
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 1, y2: 0,
                    colorStops: [{
                        offset: 0, color: '#00d4ff'
                    }, {
                        offset: 1, color: '#ff0050'
                    }]
                },
                curveness: 0.3
            },
            emphasis: {
                lineStyle: {
                    width: 4
                }
            },
            effect: {
                show: true,
                period: 3,
                trailLength: 0.3,
                symbol: 'circle',
                symbolSize: 5
            }
        },
        // 散点标记
        {
            type: 'scatter',
            coordinateSystem: 'geo',
            data: chinaCityData,
            symbolSize: v => v[2],
            itemStyle: {
                color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                    { offset: 0, color: 'rgb(251, 118, 123)' },
                    { offset: 1, color: 'rgb(204, 46, 72)' }
                ])
            },
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(255, 255, 255, 0.5)'
                }
            }
        }
    ]
});

/* 2. 实时流量趋势 */
const trendChart = echarts.init($('#realtimeTrend'));
const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
let trendData = Array.from({ length: 24 }, () => random(600, 900));

// 初始化趋势图
function initTrendChart() {
    trendChart.setOption({
        backgroundColor: 'transparent',
        grid: { left: 40, right: 20, top: 20, bottom: 40 },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        xAxis: {
            type: 'category',
            data: hours,
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { 
                color: '#ffffff', // 更亮的颜色使数字更清晰
                fontSize: 12,
                formatter: '{value}' // 确保显示原始数字
            },
            axisTick: {
                show: true, // 显示刻度线
                lineStyle: { color: '#334455' }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.1)' // 稍微加深网格线
                }
            }
        },
        series: [{
            data: trendData,
            type: 'line',
            smooth: true,
            lineStyle: {
                width: 3,
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: '#00d4ff' }, 
                    { offset: 1, color: '#ff0050' }
                ])
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(0, 212, 255, 0.3)' },
                    { offset: 1, color: 'rgba(255, 0, 80, 0.1)' }
                ])
            },
            // 添加动态散点
            markPoint: {
                symbol: 'circle',
                symbolSize: 6,
                data: [
                    { type: 'max', name: '最大值' },
                    { type: 'min', name: '最小值' }
                ],
                label: {
                    show: false
                },
                itemStyle: {
                    color: '#ff0050'
                }
            }
        }]
    });
}

initTrendChart();

/* 3. 区域分布 */
const regionChart = echarts.init($('#regionChart'));
const regionData = [
    { name: '广东', value: 28560 },
    { name: '北京', value: 21345 },
    { name: '上海', value: 20134 },
    { name: '浙江', value: 18976 },
    { name: '江苏', value: 16543 },
    { name: '四川', value: 14321 },
    { name: '山东', value: 12987 },
    { name: '河南', value: 11543 },
    { name: '湖北', value: 10321 },
    { name: '福建', value: 9876 }
];

regionChart.setOption({
    backgroundColor: 'transparent',
    grid: { left: 120, right: 20, top: 20, bottom: 20 },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        },
        formatter: '{b}: {c}人'
    },
    xAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#334455' } },
        axisLabel: { 
            color: '#ffffff', // 更亮的颜色
            fontSize: 12,
            formatter: '{value}' // 确保显示原始数字
        },
        axisTick: {
            show: true,
            lineStyle: { color: '#334455' }
        },
        splitLine: {
            lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)'
            }
        }
    },
    yAxis: {
        type: 'category',
        data: regionData.map(item => item.name).reverse(),
        axisLine: { lineStyle: { color: '#334455' } },
        axisLabel: { color: '#ffffff' }
    },
    series: [{
        type: 'bar',
        data: regionData.map(item => ({
            value: item.value,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: '#00d4ff' },
                    { offset: 1, color: '#0099cc' }
                ])
            }
        })).reverse(),
        // 添加动态效果
        emphasis: {
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: '#ff0050' },
                    { offset: 1, color: '#ff4081' }
                ])
            }
        },
        // 动画延迟效果
        animationDelay: function(idx) {
            return idx * 100;
        }
    }]
});

/* 4. 订单流 */
function pushOrder() {
    // 更新商品列表，增加更多样化的热门商品
    const goods = ['iPhone 15 Pro Max', '华为 Mate 60 Pro', 'MacBook Air M3', 'AirPods Pro 2', '索尼 PS5', 
                  '戴森吹风机', 'SK-II神仙水', '小米14 Pro', 'iPad Air 5', 'Switch OLED', 
                  '茅台飞天', '雅诗兰黛小棕瓶', 'Nike Air Max', 'Apple Watch Ultra', '大疆 Mini 4 Pro'];
    
    // 增加更多城市选择
    const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '南京', '武汉', '西安', '重庆',
                  '苏州', '天津', '郑州', '长沙', '青岛', '宁波', '厦门', '福州', '济南', '合肥'];
    
    // 增加商品分类标签
    const categories = ['数码产品', '美妆护肤', '家用电器', '奢侈品', '运动户外'];
    
    // 增加不同的购买表情图标
    const emojis = ['🎯', '🔥', '💥', '✨', '🌟', '🎉', '🎊', '🎁', '🎈', '💎'];
    
    // 增加购买渠道
    const channels = ['抖音商城', '直播带货', '达人推荐', '品牌旗舰店', '限时抢购'];
    
    const box = $('#orderStream');
    const item = document.createElement('div');
    item.className = 'data-stream-item';
    
    // 设置初始样式和动画参数
    item.style.opacity = '0';
    item.style.transform = 'translateX(-20px) scale(0.95)';
    item.style.transition = 'all 0.6s cubic-bezier(0.23, 1, 0.32, 1)';
    
    // 随机选择商品、城市、分类、表情和渠道
    const randomCity = cities[random(0, cities.length - 1)];
    const randomGood = goods[random(0, goods.length - 1)];
    const randomCategory = categories[random(0, categories.length - 1)];
    const randomEmoji = emojis[random(0, emojis.length - 1)];
    const randomChannel = channels[random(0, channels.length - 1)];
    
    // 根据商品类别调整价格范围
    let amount;
    if (randomGood.includes('iPhone') || randomGood.includes('MacBook') || randomGood.includes('华为')) {
        amount = random(5000, 15000); // 高端电子产品
    } else if (randomGood.includes('茅台') || randomGood.includes('奢侈品')) {
        amount = random(1000, 30000); // 高端消费品
    } else if (randomGood.includes('戴森') || randomGood.includes('iPad')) {
        amount = random(3000, 8000); // 中高端电子产品
    } else {
        amount = random(500, 5000); // 其他商品
    }
    
    // 格式化价格显示
    const formattedAmount = amount >= 10000 ? 
        (amount / 10000).toFixed(2) + '万' : 
        amount.toLocaleString();
    
    // 增加购买时间信息
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    const timeInfo = `${hours}:${minutes}:${seconds}`;
    
    // 为价格添加颜色标记
    const priceColor = amount > 10000 ? 'text-high-value' : amount > 5000 ? 'text-medium-value' : 'text-normal-value';
    
    // 构建更加丰富的订单信息
    item.innerHTML = `
        <div class="order-content">
            <span class="emoji">${randomEmoji}</span>
            <strong class="city">${randomCity}</strong>
            用户在 
            <span class="time-tag">${timeInfo}</span>
            通过 
            <span class="channel-tag">${randomChannel}</span>
            购买了
        </div>
        <div class="order-details">
            <span class="category-tag">${randomCategory}</span>
            类的 
            <strong class="product-name">${randomGood}</strong>
            <span class="price ${priceColor}">¥${formattedAmount}</span>
        </div>
    `;
    
    // 添加到容器并设置动画
    box.insertBefore(item, box.firstChild);
    
    // 添加出现动画
    setTimeout(() => {
        item.style.opacity = '1';
        item.style.transform = 'translateX(0) scale(1)';
    }, 50);
    
    // 添加微妙的脉冲动画效果
    setTimeout(() => {
        item.style.transform = 'translateX(0) scale(1.02)';
        setTimeout(() => {
            item.style.transform = 'translateX(0) scale(1)';
        }, 200);
    }, 300);
    
    // 限制显示数量
    if (box.children.length > 8) {
        const lastItem = box.lastChild;
        if (lastItem) {
            lastItem.style.opacity = '0';
            lastItem.style.transform = 'translateX(20px) scale(0.95)';
            setTimeout(() => {
                if (lastItem.parentNode === box) {
                    box.removeChild(lastItem);
                }
            }, 600);
        }
    }
}

// 初始填充一些数据
for (let i = 0; i < 5; i++) {
    pushOrder();
}

// 定时推送新订单
setInterval(pushOrder, 2000);

/* 数据更新函数 */
function updateRealtimeData() {
    // 更新实时指标值
    const onlineElement = document.querySelector('.realtime-item:nth-child(1) .counter');
    const videoElement = document.querySelector('.realtime-item:nth-child(2) .counter');
    const gmvElement = document.querySelector('.realtime-item:nth-child(3) .counter');
    const watchTimeElement = document.querySelector('.realtime-item:nth-child(5) .counter');
    
    // 获取当前值并动态更新
    if (onlineElement) {
        const current = parseInt(onlineElement.textContent.replace(/,/g, ''));
        const newValue = current + random(-500, 1200);
        onlineElement.textContent = newValue.toLocaleString();
        onlineElement.setAttribute('data-target', newValue);
    }
    
    if (videoElement) {
        const current = parseInt(videoElement.textContent.replace(/,/g, ''));
        const newValue = current + random(50, 200);
        videoElement.textContent = newValue.toLocaleString();
        videoElement.setAttribute('data-target', newValue);
    }
    
    if (gmvElement) {
        const current = parseInt(gmvElement.textContent.replace(/,/g, ''));
        const newValue = current + random(-50, 150);
        gmvElement.textContent = newValue.toLocaleString();
        gmvElement.setAttribute('data-target', newValue);
    }
    
    if (watchTimeElement) {
        const current = parseInt(watchTimeElement.textContent.replace(/,/g, ''));
        const newValue = Math.max(30, Math.min(60, current + random(-2, 2)));
        watchTimeElement.textContent = newValue.toLocaleString();
        watchTimeElement.setAttribute('data-target', newValue);
    }
    
    // 更新趋势图的最后一个数据点
    const lastIndex = trendData.length - 1;
    const currentValue = trendData[lastIndex];
    const newValue = Math.max(600, Math.min(900, currentValue + random(-30, 30)));
    trendData[lastIndex] = newValue;
    
    // 动态更新趋势图
    trendChart.setOption({
        series: [{
            data: trendData
        }]
    });
    
    // 更新地图点的数据
    const randomIndex = random(0, chinaCityData.length - 1);
    chinaCityData[randomIndex].value[2] = Math.max(5, Math.min(20, chinaCityData[randomIndex].value[2] + random(-3, 3)));
    
    mapChart.setOption({
        series: [
            { data: createFlyLinesData() },
            { data: chinaCityData }
        ]
    });
    
    // 更新地区数据
    const regionIndex = random(0, regionData.length - 1);
    regionData[regionIndex].value = Math.max(10000, Math.min(200000, regionData[regionIndex].value + random(-5000, 15000)));
    
    regionChart.setOption({
        yAxis: {
            data: regionData.map(item => item.name).reverse()
        },
        series: [{
            data: regionData.map(item => ({
                value: item.value,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: '#0099cc' }
                    ])
                }
            })).reverse()
        }]
    });
}

// 定时更新实时数据，每秒更新一次
setInterval(updateRealtimeData, 1000);

/* 页面进入动画 - 从上到下淡入效果 */
function pageEnterAnimation() {
    // 获取页面所有主要元素，按照从上到下的顺序排列
    const elements = [
        // 导航栏
        ...document.querySelectorAll('.navbar'),
        // 实时指标栏
        ...document.querySelectorAll('.metrics-bar'),
        // 卡片（按照它们在页面中从上到下的实际位置）
        ...Array.from(document.querySelectorAll('.card')).sort((a, b) => {
            // 根据元素在页面中的垂直位置排序
            return a.getBoundingClientRect().top - b.getBoundingClientRect().top;
        })
    ];
    
    // 为每个元素设置初始状态
    elements.forEach(element => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(30px)';
        element.style.transition = 'opacity 0.8s ease, transform 0.8s ease';
    });
    
    // 按照从上到下的顺序依次淡入元素
    elements.forEach((element, index) => {
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, 200 + index * 200); // 每个元素间隔200ms，形成流畅的从上到下效果
    });
}

// 页面加载完成后执行动画
window.addEventListener('load', pageEnterAnimation);

/* 响应式重绘 */
window.addEventListener('resize', () => {
    mapChart.resize();
    trendChart.resize();
    regionChart.resize();
});